/**
   Copyright 2011 Фроловский А. В.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
   
   This file is a part of MyStats project
 */

package foo.mystats;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.app.ActionBarActivity;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import foo.mystats.contentprovider.DataContentProvider;
import foo.mystats.db.DataTable;
import foo.mystats.db.RowTable;

public class DataListActivity extends ActionBarActivity implements OnClickListener,
    LoaderManager.LoaderCallbacks<Cursor> {

  public static String PARAM_ROW_ID = "row_id";
  public static String PARAM_ROW_NAME = "row_name";
  public static String PARAM_ROW_DATA_TYPE = "row_data_type";
  public static String PARAM_ROW_IS_TIME_NEEDED = "row_is_time_needed";
  private ListView lv;

  private long rowId;
  private int rowDataType;
  private boolean isTimeNeeded;
  private String rowName;
  private long selectedDataId;

  private DataListCursorAdapter adapter;

  private AlertDialog deleteConfirmAlert;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    this.rowId = getIntent().getExtras().getLong(PARAM_ROW_ID);
    this.rowName = getIntent().getExtras().getString(PARAM_ROW_NAME);
    this.rowDataType = getIntent().getExtras().getInt(PARAM_ROW_DATA_TYPE);
    this.isTimeNeeded = getIntent().getExtras().getBoolean(PARAM_ROW_IS_TIME_NEEDED);

    setContentView(R.layout.data_list);

    lv = (ListView) findViewById(R.id.datalist_listview);
    lv.setOnItemClickListener(onClickListener);
    registerForContextMenu(lv);

    setTitle(this.rowName);

    fillData();
  }

  private void fillData() {
    adapter = new DataListCursorAdapter(this, null, 0);
    lv.setAdapter(adapter);

    getSupportLoaderManager().initLoader(0, null, this);
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.data_list_options, menu);
    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case R.id.data_list_options_menu_add:
        Intent dataEditActivity = new Intent(this, DataEditActivity.class);
        dataEditActivity.putExtra(PARAM_ROW_ID, this.rowId);
        dataEditActivity.putExtra(PARAM_ROW_DATA_TYPE, this.rowDataType);
        dataEditActivity.putExtra(PARAM_ROW_IS_TIME_NEEDED, this.isTimeNeeded);
        startActivity(dataEditActivity);
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  @Override
  public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    getMenuInflater().inflate(R.menu.data_list_context, menu);

    Cursor c = (Cursor) lv.getItemAtPosition(((AdapterContextMenuInfo) menuInfo).position);
    if (c != null) {
      selectedDataId = c.getLong(c.getColumnIndexOrThrow(BaseColumns._ID));
      menu.setHeaderTitle(DataListCursorAdapter.getValueAsString(this, c));
    }
  }

  @Override
  public boolean onContextItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case R.id.data_list_context_menu_edit:
        startEditDataActivity();
        return true;
      case R.id.data_list_context_menu_delete:
        showDeleteConfirmationDialog();
        return true;
      default:
        return super.onContextItemSelected(item);
    }
  }

  public void showDeleteConfirmationDialog() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this)
        .setMessage(R.string.msg_data_delete_confirm)
        .setCancelable(false)
        .setPositiveButton(R.string.yes, this)
        .setNegativeButton(R.string.no, this);
    deleteConfirmAlert = builder.create();
    deleteConfirmAlert.show();
  }

  @Override
  public void onClick(DialogInterface dialog, int which) {
    if (dialog == deleteConfirmAlert) {
      switch (which) {
        case DialogInterface.BUTTON_POSITIVE:
          Uri uri = Uri.parse(DataContentProvider.CONTENT_URI + "/" + selectedDataId);
          getContentResolver().delete(uri, null, null);
          fillData();
          break;
        case DialogInterface.BUTTON_NEGATIVE:
          dialog.dismiss();
          break;
      }
    }
  }

  public void startEditDataActivity() {
    Intent editDataActivity = new Intent(this, DataEditActivity.class);
    editDataActivity.putExtra("data_uri", Uri.parse(DataContentProvider.CONTENT_URI + "/" + selectedDataId));
    startActivity(editDataActivity);
  }

  OnItemClickListener onClickListener = new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    }
  };

  @Override
  public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    return getLoader(this, this.rowId);
  }

  public static Loader<Cursor> getLoader(Context con, long rowId) {
    String[] projection = {
        DataTable.TABLE_DATA + "." + DataTable.COLUMN_ID + " AS " + BaseColumns._ID,
        DataTable.COLUMN_DATETIME + " AS " + DataTable.COLUMN_DATETIME,
        DataTable.COLUMN_VALUE + " AS " + DataTable.COLUMN_VALUE,
        DataTable.COLUMN_ROW_ID + " AS " + DataTable.COLUMN_ROW_ID,
        RowTable.COLUMN_DATA_TYPE + " AS " + RowTable.COLUMN_DATA_TYPE,
        RowTable.COLUMN_IS_TIME_NEEDED + " AS " + RowTable.COLUMN_IS_TIME_NEEDED,
    };

    String selection = DataTable.COLUMN_ROW_ID + " = ?";
    String[] selectionArgs = { String.valueOf(rowId) };
    String sortOrder = DataTable.COLUMN_DATETIME + " DESC";

    return new CursorLoader(con, DataContentProvider.CONTENT_URI, projection, selection, selectionArgs, sortOrder);
  }

  @Override
  public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
    adapter.swapCursor(cursor);
  }

  @Override
  public void onLoaderReset(Loader<Cursor> loader) {
    adapter.swapCursor(null);
  }
}
